package interfaz;

import clases.*;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;

/**
 *
 * @author sergio crisologo
 */
public class dlgUsuariosMantenimiento extends javax.swing.JDialog {

    private ClsDatabase bd = new ClsDatabase();
//    private ClsSeguridad seguridad = new ClsSeguridad();
//    private ClsSesion sesion = new ClsSesion();
    private ClsMetodos metodos = new ClsMetodos();
    DefaultComboBoxModel mlb = new DefaultComboBoxModel();
    /**
     * Creates new form dlgUsuarios
     *
     * @param parent
     * @param modal
     */
    String idusuario = "";
    String nombre_usuario = "";
    int transaccion = 1;

    public dlgUsuariosMantenimiento(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        setLocationRelativeTo(null);
        metodos._iconJDialog(this);
        cargar_usuario("");
        metodos.tablaOcultarcolumnas(tblUsuarios, new int[]{0,4});
    }

    public void cargar_usuario(String nombre) {
        metodos.tablaLlenaSql_defecto(tblUsuarios, "u.idusuario, u.nombre,u.nombre_usuario,ut.descripcion,u.estado ","FROM usuario u, usuario_tipo ut where u.idusuario_tipo=ut.idusuario_tipo and u.nombre like '" + nombre + "%' ");
//        metodos.tablaLlenaSql(tblUsuarios, "SELECT u.nombre,u.nombre_usuario,ut.descripcion,u.estado FROM usuario u, usuario_tipo ut where u.idusuario_tipo=ut.idusuario_tipo and u.nombre like '" + nombre + "%' ");
    }

    public void usuario_formulario() {
        int fila_seleccionada = tblUsuarios.getSelectedRow();
        if (fila_seleccionada != -1) {
            //System.out.println( array_id_usuario_tipo[fila_seleccionada][0]);
            String descripcion_tipo_usuario = tblUsuarios.getValueAt(fila_seleccionada, 0).toString();
            txtBuscar.setText(descripcion_tipo_usuario);
            /*
             * lista de formularios faltantes
             */
//            metodos.tablaLlenaSql(jTable2, "SELECT nombre FROM formulario", 1);
        }
    }

    public void eliminar() {
        int fila = tblUsuarios.getSelectedRow();
        if (fila != -1) {
            if (JOptionPane.showConfirmDialog(null, "Esta seguro de eliminar este Usuario", "Mensaje", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == 0) {
                String id = tblUsuarios.getValueAt(fila, 0).toString();
                boolean seRepite = bd.verif_repite("SELECT idinsumo FROM insumo WHERE idusuario='" + id + "'");
                if (!seRepite) {
                    bd.delete("usuario", " idusuario='" + tblUsuarios.getValueAt(fila, 0) + "'");
                    cargar_usuario("");
                } else {
                    JOptionPane.showMessageDialog(null, "No se puede eliminar este Usuario, esta siendo usado!!!");
                }
            }

        } else {
            javax.swing.JOptionPane.showMessageDialog(this, "Seleccione el Usuario");
        }
    }

    public void limpiar() {
        txtBuscar.setText("");
        cargar_usuario("");
    }

    public void buscar() {
        cargar_usuario(txtBuscar.getText());
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        shapeTabbedPaneUI1 = new util.shapeTabbedPaneUI();
        shapeTabbedPaneUI2 = new util.shapeTabbedPaneUI();
        pln1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblUsuarios = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        txtBuscar = new javax.swing.JTextField();
        btnAgregar = new javax.swing.JButton();
        btnEditar = new javax.swing.JButton();
        btnEliminar = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jLabel10 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Usuarios");
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        pln1.setBackground(new java.awt.Color(225, 235, 247));
        pln1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        tblUsuarios.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "id", "Nombre", "Usuario", "Tipo", "Estado"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                true, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblUsuarios.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_NEXT_COLUMN);
        tblUsuarios.setOpaque(false);
        tblUsuarios.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        tblUsuarios.setShowHorizontalLines(false);
        tblUsuarios.setShowVerticalLines(false);
        tblUsuarios.getTableHeader().setReorderingAllowed(false);
        tblUsuarios.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblUsuariosMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tblUsuarios);

        pln1.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 91, 674, 372));

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Buscar"));
        jPanel1.setOpaque(false);
        jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel2.setText("Nombre:");
        jPanel1.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 24, -1, 25));

        txtBuscar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtBuscarKeyReleased(evt);
            }
        });
        jPanel1.add(txtBuscar, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 24, 340, 25));

        pln1.add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 9, 674, 70));

        btnAgregar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/peque/agregar.png"))); // NOI18N
        btnAgregar.setText("Crear");
        btnAgregar.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAgregarActionPerformed(evt);
            }
        });
        pln1.add(btnAgregar, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 480, -1, -1));

        btnEditar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/peque/editar.png"))); // NOI18N
        btnEditar.setText("Editar");
        btnEditar.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnEditar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditarActionPerformed(evt);
            }
        });
        pln1.add(btnEditar, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 480, -1, -1));

        btnEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/peque/borrar.png"))); // NOI18N
        btnEliminar.setText("Eliminar");
        btnEliminar.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarActionPerformed(evt);
            }
        });
        pln1.add(btnEliminar, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 480, -1, -1));

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/peque/salir.png"))); // NOI18N
        jButton1.setText("Salir");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        pln1.add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(580, 480, 102, -1));

        jLabel10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/fondo_dialog.jpg"))); // NOI18N
        pln1.add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 450, -1));

        getContentPane().add(pln1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 710, 520));

        setBounds(0, 0, 724, 557);
    }// </editor-fold>//GEN-END:initComponents

    private void btnAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregarActionPerformed
//        ver_nuevo();
        dlg_NewUsuario dialog = new dlg_NewUsuario(new javax.swing.JFrame(), true, this, tblUsuarios);
        dialog.setTitle("Nuevo Usuario");
        dialog.Nuevo();
        dialog.setVisible(true);
    }//GEN-LAST:event_btnAgregarActionPerformed

    private void btnEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditarActionPerformed
//        ver_editar();
        dlg_NewUsuario dialog = new dlg_NewUsuario(new javax.swing.JFrame(), true, this, tblUsuarios);
        dialog.setTitle("Editar Usuario");
        dialog.ver_editar();
    }//GEN-LAST:event_btnEditarActionPerformed

    private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed
        eliminar();
    }//GEN-LAST:event_btnEliminarActionPerformed

    private void tblUsuariosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblUsuariosMouseClicked
        if (evt.getClickCount() == 2) {
//      JTable target = (JTable)evt.getSource();
//      int row = target.getSelectedRow();
//      ...
//            ver_editar();
            dlg_NewUsuario dialog = new dlg_NewUsuario(new javax.swing.JFrame(), true, this, tblUsuarios);
            dialog.setTitle("Editar Usuario");
            dialog.ver_editar();
        }
    }//GEN-LAST:event_tblUsuariosMouseClicked

    private void txtBuscarKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtBuscarKeyReleased
        String nombre = txtBuscar.getText().toString();
        cargar_usuario(nombre);
    }//GEN-LAST:event_txtBuscarKeyReleased

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        dispose();
    }//GEN-LAST:event_jButton1ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(dlgUsuariosMantenimiento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(dlgUsuariosMantenimiento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(dlgUsuariosMantenimiento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(dlgUsuariosMantenimiento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the dialog
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                dlgUsuariosMantenimiento dialog = new dlgUsuariosMantenimiento(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAgregar;
    private javax.swing.JButton btnEditar;
    private javax.swing.JButton btnEliminar;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPanel pln1;
    private util.shapeTabbedPaneUI shapeTabbedPaneUI1;
    private util.shapeTabbedPaneUI shapeTabbedPaneUI2;
    private javax.swing.JTable tblUsuarios;
    private javax.swing.JTextField txtBuscar;
    // End of variables declaration//GEN-END:variables
}
